package com.github.raffle.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Jerry Liu
 * @since 2017/5/8
 */
public class DefaultThreadFactory implements ThreadFactory {

    private AtomicLong count = new AtomicLong(1);
    private static final String DEFAULT_THREAD_NAME_PREFIX = "";
    private ThreadGroup group;
    private String threadNamePrefix = DEFAULT_THREAD_NAME_PREFIX;

    public DefaultThreadFactory() {
        this(DEFAULT_THREAD_NAME_PREFIX);
    }

    public DefaultThreadFactory(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
        ThreadGroup root = getRootThreadGroup();
        group = new ThreadGroup(root, threadNamePrefix);
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(group, r);
        thread.setName(threadNamePrefix + "-" + count.getAndIncrement());
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }

        if (Thread.NORM_PRIORITY != thread.getPriority()) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }

    private ThreadGroup getRootThreadGroup() {
        ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        while (threadGroup.getParent() != null) {
            threadGroup = threadGroup.getParent();
        }
        return threadGroup;
    }
}
